package com.aaa.interceptor;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.java.Log;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author ：张恒（1371745897@qq.com）
 * @date ：Created in 2022/9/7 21:43
 * @description：拦截器
 * @modified By：
 * @version: 1.0
 */
@Log
public class FirstInterceptor implements HandlerInterceptor {
    /**
     * @create by: 张恒
     * @description:controller中的方法之前执行
     * 返回true则继续执行controller中的方法
     * 返回false停止执行controller中的方法
     * @create time: 2022/9/7 21:47
     * @param request
     * @param response
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("controller中方法之前开始执行了");
        //如果用户为登录，拦截，并让他离开，去登录页面
        String contextPath = request.getContextPath();
        HttpSession session = request.getSession();
        //排除不需要拦截的资源
        String uri = request.getRequestURI();
        log.info(uri);
        if (uri.contains("login")||uri.contains("front")||uri.contains("static")){
            return true;
        }else {

            Object userObj = session.getAttribute("user");
            //如果用户已经登录，放行
            if (ObjectUtil.isNotEmpty(userObj)){
                return true;
            }else {
                response.sendRedirect(contextPath+"/login.jsp");
                return false;
            }
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("controller中方法之后开始执行了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("请求完成开始执行");
    }
}